package main

import (
	"bytes"
	"context"
	"embed"
	"errors"
	"flag"
	"gin_reptile/pkg/db"
	. "gin_reptile/pkg/global"
	"gin_reptile/pkg/util"
	"gin_reptile/pkg/viper"
	"github.com/gin-gonic/gin"
	"github.com/go-co-op/gocron"
	"github.com/gogf/gf/v2/os/glog"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	env = flag.String("e", "", "env")
)

//go:embed config/dev.toml
//go:embed config/prod.toml
var FS embed.FS

func main() {
	// 初始化配置文件
	flag.Parse()

	// 初始化viper
	viper.InitViper()

	var by []byte
	if *env == "dev" {
		by, _ = FS.ReadFile("config/dev.toml")
	} else if *env == "prod" {
		by, _ = FS.ReadFile("config/prod.toml")
	}
	viper.ReadConfig(bytes.NewBuffer(by))

	// 初始化日志
	Logger = glog.New()

	// 初始化数据库
	db.InitGorm()

	engine := gin.Default()

	srv := &http.Server{
		Addr:         "0.0.0.0:7001",
		Handler:      engine,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
	}
	log.Printf("Listen port start：%s", "7001")

	// 启动服务
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	util.GetCurrencyApiData()
	timezone, _ := time.LoadLocation("Asia/Shanghai")
	s := gocron.NewScheduler(timezone)

	s.Cron("0 8-20 * * *").Do(util.GetCurrencyApiData)
	s.StartBlocking()

	quit, stop := signal.NotifyContext(context.Background(), syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, os.Interrupt, os.Kill)
	defer stop()
	<-quit.Done()
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
